package cn.com.onlinetextproject.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class ErrorController extends BasicErrorController {
    
    private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);

    public ErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, new ErrorProperties());
    }

    @RequestMapping(value = "/error", produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = getErrorAttributes(request, false);
        
        // 获取异常信息
        String error = (String) model.get("error");
        String message = (String) model.get("message");
        String path = (String) model.get("path");
        
        logger.error("Error: {}, Message: {}, Path: {}", error, message, path);
        
        // 检查是否是StudentList页面的错误
        if (path != null && path.contains("/StudentList") && 
            message != null && message.contains("templates/teacher/StudentList.html")) {
            return new ModelAndView("error/studentlist-error");
        }
        
        // 其他错误使用默认处理
        ModelAndView modelAndView = super.errorHtml(request, response);
        return modelAndView;
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        return super.error(request);
    }
} 